//
//  Headers.swift
//  MyLibrary
//
//  Created by 周博 on 2020/6/17.
//  Copyright © 2020 ncit. All rights reserved.
//


/**
 * 通用Headers
 */
import UIKit

///MARK: 设备宽高
public let SCREEN_WIDTH = UIScreen.main.bounds.size.width
public let SCREEN_HEIGHT = UIScreen.main.bounds.size.height
public let SCREEN_BOUNDS = UIScreen.main.bounds
public let SCREEN_SIZE = UIScreen.main.bounds.size
public let SCREENMIN = min(SCREEN_WIDTH, SCREEN_HEIGHT)
public let SCREENMAX = max(SCREEN_WIDTH, SCREEN_HEIGHT)
// 屏幕高比宽
public let SCREEN_RADIO = SCREEN_HEIGHT / SCREEN_WIDTH


// keyWindow
public let KEY_WINDOW = UIApplication.shared.keyWindow



/// 状态栏高度获取
public var STATUS_BAR_HEIGHT: CGFloat {

    if #available(iOS 13.0, *) {
        let statusBarManager = UIApplication.shared.windows.first?.windowScene?.statusBarManager
        return (statusBarManager?.statusBarFrame.size.height) ?? 20
    }
    else {
        return UIApplication.shared.statusBarFrame.size.height
    }
}

/// 导航栏高度获取
public let NAV_BAR_HEIGHT = (STATUS_BAR_HEIGHT + 44) as CGFloat

/// SAFE AREA高度
public let SAFE_AREA_HEIGHT = UIScreen.main.bounds.height - NAV_BAR_HEIGHT - (NAV_BAR_HEIGHT > 64.0 ? 34.0 : 0.0)

///  TABBAR 高度获取
public let TAB_BAR_HEIGHT =  (UIScreen.main.bounds.size.height >= 812 ? 83 : 49) as CGFloat

/// 是否为iphonex系列
public let ISIPHONEX = STATUS_BAR_HEIGHT > 20 ? true : false


// iPhonex系列底部控制条高度
public let CONTROL_BAR_HEIGHT = ISIPHONEX ? 34.float_value : 0.float_value

/// xib开发颜色相关

let whiteString = "white_"  // 白色

enum XibColor: String {
    case white
    case clear
    case black
//    case red
//    case blue
//    case purple
//    case gray
//    case cyan           // 青色 (蓝绿)
//    case green
//    case pink
//    case orange
//    case brown
//    case sky            // 天蓝 (66, 188, 209)
//    case lilac          // 浅紫色
}


//MARK:版本号相关
public let ZB_INFO = Bundle.main.infoDictionary!
public let ZB_DisplayName   = ZB_INFO["CFBundleDisplayName"]               //程序名称
public let ZB_ShortVersion  = ZB_INFO["CFBundleShortVersionString"]        //主程序版本号
public let ZB_BuildVersion  = ZB_INFO["CFBundleVersion"]                   //版本号（内部标示）
public let ZB_BundleId      = ZB_INFO["CFBundleIdentifier"]                //bundleId
public let ZB_ProjectName   = ZB_INFO["CFBundleExecutable"]                //工程名


///设备信息
public let ZB_Device_Version = UIDevice.current.systemVersion //iOS版本
public let ZB_Device_Udid = UIDevice.current.identifierForVendor //设备udid
public let ZB_Device_SystemName = UIDevice.current.systemName //设备名称
public let ZB_Device_Model = UIDevice.current.model //设备型号
public let ZB_Device_Name = UIDevice.current.name //设备具体型号
public let ZB_Device_LocalizedModel = UIDevice.current.localizedModel //设备区域化型号如A1533


/// 发送通知
public func postNotification(name: String, object: Any?, userInfo: [AnyHashable: Any]?) {
    NotificationCenter.default.post(name: NSNotification.Name(rawValue: name), object: object, userInfo: userInfo)
}

/// 添加通知观察者
public func addNotificationObserver(forName: String, object: Any?, queue: OperationQueue?, using: @escaping (Notification) -> Void) -> NSObjectProtocol {
    return NotificationCenter.default.addObserver(forName: Notification.Name(rawValue: forName), object: object, queue: queue, using: using)
}

/// 移除观察者
public func removeAllObserver(observer: Any) {
    NotificationCenter.default.removeObserver(observer)
}

/// 获取当前顶层控制器
public func topViewController() -> UIViewController? {
    return UIApplication.shared.keyWindow?.topViewController()
}

public let printFileName = "/log.txt"

/// log写入
public func printfile(_ items: String..., separator: String = " ", terminator: String = "\n", isNeedAppend: Bool = true) {

    var string = ""
    
    for itemString in items {
        string += itemString
        string += separator
    }
    
    string += terminator
    
    let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    let pathDirectory = paths.first! + "/log"
    let pathFile = pathDirectory + printFileName
    
    
    let fileManager = FileManager.default
    let logString = logFormat(logString: string)
    
    
    if isNeedAppend && fileManager.fileExists(atPath: pathFile) {
        
        // 追加写入
        guard let fileHandle = FileHandle.init(forWritingAtPath: pathFile) else {
            return
        }

        fileHandle.seekToEndOfFile()

        // 以utf-8编码的方式写入数据, 其实就是字符串
        fileHandle.write(logString.data(using: .utf8) ?? Data())
        fileHandle.closeFile()
    } else {
        logString.write(toFile: pathFile)
    }
}


public func cleanPrintFile(){
    let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    let path = paths.first! + "/log" + printFileName
    try? FileManager.default.removeItem(atPath: path)
}

private func logFormat(logString: String) -> String {
    let date = Date()
    let dateString = date.dateString(format: TimeFormat.yearSecWithLine.rawValue)
    
    return "\n================================start================================\n\n"
        + logString
        + "\n========================( \(dateString) )============================\n\n"
}


/**
 * 当前时间戳转时间字符
 */
public func getDateFormatString(timeStamp: String, format: String = "HH") -> String {
    
    let interval: TimeInterval = TimeInterval.init(timeStamp)!
    
    let date = Date(timeIntervalSince1970: interval)
    
    let dateformatter = DateFormatter()
    
    //自定义日期格式
    
    dateformatter.dateFormat = format
    
    return dateformatter.string(from: date)
    
}

/**
 * 当前时间转时间戳
 */
public func getCurrentTimeStamp() ->String{
    
    let nowDate = Date.init()
    
    //10位数时间戳
    
    let interval = Int(nowDate.timeIntervalSince1970)
    
    //13位数时间戳 (13位数的情况比较少见)
    
    // let interval = CLongLong(round(nowDate.timeIntervalSince1970*1000))
    
    return "\(interval)"
}


public let libBundle = Bundle.main.path(forResource: "zblib.bundle", ofType: nil)
public let libBundlePath = Bundle.main.bundlePath + "/zblib.bundle"
public let libPlayerBundlePath = libBundlePath + "/播放器"


